#include "exp_4.h"
//线性表序号为0的元素闲置
//线性表满时，capacity比size大1
Status SqList_init(SqList *L) {
    // 分配指定容量的内存，如果分配失败，则返回NULL
    L->data = (Node **)malloc(LIST_INIT_SIZE * sizeof(Node *));
    if (L->data == NULL) {
        // 存储内存失败
        exit(OVERFLOW);
    }
    L->size = 0;
    L->capacity = LIST_INIT_SIZE;
    return OK;
}

Status SqList_init_capacity(SqList *L, int _capacity) {
    // 分配指定容量的内存，如果分配失败，则返回NULL
    L->data = (Node **)malloc((_capacity + 1) * sizeof(Node *));
    if (L->data == NULL) {
        // 存储内存失败
        exit(OVERFLOW);
    }
    L->size = 0;
    L->capacity = _capacity + 1;
    return OK;
}

Status SqList_destroy(SqList *L) {
    if (L == NULL || L->data == NULL) {
        return ERROR;
    }
    // 释放顺序表内存
    free(L->data);
    // 释放内存后置空指针
    L->data = NULL;
    // 顺序表长度跟容量都归零
    L->size = 0;
    L->capacity = 0;
    return OK;
}

Status SqList_valid(SqList *L) {
    if (L == NULL || L->data == NULL) {
        return TRUE;
    } else {
        return FALSE;
    }
}

Status SqList_at(SqList *L, int i, Node **e) {
    if (i <= 0 || i > L->size) {
        return ERROR;
    }
    *e = L->data[i];
    return OK;
}

void SqList_traverse(SqList *L, void (*visit)(Node **)) {
    int i;
    for (i = 1; i <= L->size; i++) {
        visit(&L->data[i]);
    }
}

int SqList_size(SqList *L) { return L->size; }

Status SqList_changeSize(SqList *L) {
    Node **tmp;
    // 基于现有空间扩容
    tmp = L->data;
    L->capacity += LIST_INCREASE;
    L->data = (Node **)realloc(L->data, L->capacity);
    //扩容失败，分配了新的内存空间
    if (tmp != L->data) {
        for (int i = 1; i <= L->size; ++i) {
            L->data[i] = tmp[i];
        }
    }
    if (L->data == NULL) {
        // 存储内存失败
        exit(OVERFLOW);
    }
}

Status SqList_insert(SqList *L, int index, Node **e) {
    Node **tmp;
    if (SqList_valid(L)) {
        return ERROR;
    }
    if (index <= 0 || index > L->size + 1) {
        return ERROR;
    }
    if (L->size >= L->capacity - 1) {
        SqList_changeSize(L);
    }
    for (int i = L->size; i > index; --i) {
        L->data[i] = L->data[i - 1];
    }
    L->data[index] = *e;
    ++L->size;
    return OK;
}

Status SqList_pushBack(SqList *L, Node **e) {
    return SqList_insert(L, L->size + 1, e);
}
Status SqList_pop(SqList *L, Node **e) { --L->size; }

Status SqList_erase(SqList *L, int index) {
    Node **mov;
    if (SqList_valid(L)) {
        return ERROR;
    }
    if (index < 0 || index > L->size) {
        return ERROR;
    }
    for (int i = index + 1; i <= L->size; ++i) {
        L->data[i - 1] = L->data[i];
    }
    --L->size;
    return OK;
}

Status SqList_clear(SqList *L) {
    // 确保顺序表结构存在
    if (SqList_valid(L)) {
        return ERROR;
    }
    L->size = 0;
    return OK;
}